package cn.fscode.code.generator.controller;

import cn.fscode.commons.core.response.Resp;
import cn.fscode.commons.tool.core.exception.BizException;
import cn.fscode.commons.tool.core.file.FileUtils;
import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author shenguangyang
 */
@Slf4j
@RestController
@RequestMapping("/api/share")
public class ShareController {
    private File saveFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new BizException("未选择文件");
        }
        // 获取上传文件原来的名称
        String filename = file.getOriginalFilename();
        String userDir = System.getProperty("user.dir");
        String filePath = userDir + java.io.File.separator + "upload-file" + java.io.File.separator;
        FileUtils.mkdirs(filePath);
        File localFile = new File(filePath + UUID.randomUUID() + "__" + filename);
        try {
            // 把上传的文件保存至本地
            file.transferTo(localFile);
        } catch (IOException e) {
            log.error("errorMessage: {}", e.getMessage());
            throw new BizException("上传失败");
        }
        return localFile;
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public Resp<String> upload(@RequestParam("file") MultipartFile file) {
        File localFile = saveFile(file);
        return Resp.ok(localFile.getAbsolutePath());
    }
}
